<?php

class Testing extends AppModel
{

	public $name = 'Testing';

	public $displayField = 'date';

	protected $pass_statuses = array(
	   'READY',
	   'IN_PROGRESS',
	   'PASSED',
	);

	public $validate = array(
	);

	public $belongsTo = array(
        'Candidate' => array('className' => 'Candidate'),
        'Test' => array('className' => 'Test'),
        'Client' => array('className' => 'Client'),
	);
	public $hasMany = array(
        'Reportings' => array('className' => 'Reporting'),
	);
	public $hasOne = array(
        'Pass' => array('className' => 'Pass'),
	);
	protected $before_delete_auth_link = null;

	function allowDelete($fields = null)
	{
        return false;
	}

	function allowUpdate($fields = null)
	{
        return true;
	}

	function generateList($conds = array())
	{
	    $this->rel();
        return parent::generateList($conds, $this->primaryKey, null, "{n}.{$this->name}.{$this->primaryKey}", "{n}.{$this->name}.{$this->displayField}");
	}

    function getUniqueCode($length = 0)
    {
        $code = md5(uniqid(rand(), true));
        if ($length > 0) return substr($code, 0, $length);
        else return $code;
    }

	/**
	 * Кеширование client_id, для оптимизации.
	 */
	//////////////////////////////////////////////////////
	protected function get_client_id_by_candidate_id($candidate_id)
	{
	    if (is_null($candidate_id)) {
	        return null;
	    }
        $this->Candidate->rel();
        $candidate = $this->Candidate->read("`{$this->Candidate->name}`.`client_id`", $candidate_id);
        if (empty($candidate[$this->Candidate->name]['client_id'])) {
            throw new DBException();
        }

        return $candidate[$this->Candidate->name]['client_id'];
	}

	protected function beforeChange_candidate_id($new, $old)
	{
        $this->data[$this->name]['client_id'] = $this->get_client_id_by_candidate_id($new);
        return true;
	}

	function beforeSave()
	{
	    if (! $this->exists()) {
	        $candidate_id = isset($this->data[$this->name]['candidate_id']) ? $this->data[$this->name]['candidate_id'] : null;
            $this->data[$this->name]['client_id'] = $this->get_client_id_by_candidate_id($candidate_id);

            $this->data[$this->name]['date'] = Date::Unix2SQL(time());

    	    if (isset($this->data[$this->name]['pass_status'])) {
    	        if ($this->data[$this->name]['pass_status'] === 'PASSED') {
        	        if (empty($this->data[$this->name]['result_source'])) {
            	        $this->data[$this->name]['result_source'] = "APPLET";
        	        }
        	        if (empty($this->data[$this->name]['ip'])) {
                        $this->data[$this->name]['ip'] =  env('REMOTE_ADDR');
        	        }
        	        $this->data[$this->name]['pass_date'] = Date::Unix2SQL(time());
    	        } else {
                    if ($this->data[$this->name]['pass_status'] == "READY") {
                        $this->addLineFromAppletsMapFileForCurrent();
                    } elseif ($this->data[$this->name]['pass_status'] == "IN_PROGRESS") {
            	        $this->data[$this->name]['in_progress_date'] = Date::Unix2SQL(time());
                    } else {
            	        $this->data[$this->name]['in_progress_date'] = null;
                    }
        	        $this->data[$this->name]['pass_date'] = null;
        	        $this->data[$this->name]['result_source'] = null;
    	        }
    	    } else { // Предполагается, что по умолчанию pass_status READY.
                $this->addLineFromAppletsMapFileForCurrent();
    	        $this->data[$this->name]['pass_date'] = null;
    	        $this->data[$this->name]['in_progress_date'] = null;
    	        $this->data[$this->name]['result_source'] = null;
    	    }
	    }

	    return parent::beforeSave();
	}
	//////////////////////////////////////////////////////

	function beforeChange_pass_status($new, $old)
	{
	    if ($new === 'PASSED') {
	        $this->data[$this->name]['pass_date'] = Date::Unix2SQL(time());
	        if (empty($this->data[$this->name]['ip'])) {
                $this->data[$this->name]['ip'] =  env('REMOTE_ADDR');
	        }
	        if (empty($this->data[$this->name]['result_source'])) {
    	        $this->data[$this->name]['result_source'] = "APPLET";
	        }
	    } else {
	        $this->data[$this->name]['result_source'] = null;
	        $this->data[$this->name]['result'] = null;
	        if ($new == 'READY') {
    	        $this->data[$this->name]['date'] = Date::Unix2SQL(time());
            } elseif ($new == "IN_PROGRESS") {
    	        $this->data[$this->name]['in_progress_date'] = Date::Unix2SQL(time());
            } else {
    	        $this->data[$this->name]['in_progress_date'] = null;
            }
	        $this->data[$this->name]['pass_date'] = null;
	    }
	    return true;
	}

	function allowCancel($fields = null)
	{
	    if (!isset($fields)) {
	        return true;
	    }
	    if (empty($fields['pass_status'])) {
	        return false;
	    }
	    $result = ($fields['pass_status'] == 'READY');
	    if (Auth::o()->is('admin')) {
	        $result |= ($fields['pass_status'] == 'IN_PROGRESS');
	    }

	    return $result;
	}

	/**
	 * Отмена назначенного инструмента.
	 *
	 * @param array $data
	 */
	function cancel($data)
	{
	    if (! $this->allowCancel($data[$this->name])) {
            return false;
	    }
	    if ($data[$this->name]['pass_status'] == 'READY') {
	        return $this->del($data[$this->name][$this->primaryKey]);
	    } elseif ($data[$this->name]['pass_status'] == 'IN_PROGRESS') {
	        $id = $data[$this->name][$this->primaryKey];
	        $data = array();
	        $data[$this->name][$this->primaryKey] = $id;
	        $data[$this->name]['pass_status'] = 'READY';
	        return $this->save($data);
	    }
	    return false;
	}

	function getPassStatuses()
	{
	    return $this->pass_statuses;
	}

	function getPassStatusesList()
	{
	    $result = array();
	    foreach ($this->pass_statuses as $pass_status) {
	        $result[$pass_status] = __d('testings', 'pass_status_'.$pass_status, true);
	    }
	    return $result;
	}

	function beforeDelete()
	{
	    $this->before_delete_auth_link = null;
        $fields = $this->getStoredFields(array("auth_link"));
        if (isset($fields)) {
            $this->before_delete_auth_link = $fields["auth_link"];
        }

        return true;
	}

	function afterDelete()
	{
        if (isset($this->before_delete_auth_link)) {
	        $this->delLineFromAppletsMapFile($this->before_delete_auth_link);
        }
	}

	function afterChange_pass_status($new, $old)
	{
	    if ($new === 'READY') {
	        $this->addLineFromAppletsMapFileForCurrent();
	    } else {
            $fields = $this->getStoredFields(array("auth_link"));
            if (isset($fields)) {
                $hash = $fields["auth_link"];
    	        $this->delLineFromAppletsMapFile($hash);
            }
	    }
	}

	protected function addLineFromAppletsMapFileForCurrent()
	{
        $fields = $this->getStoredFields(array("auth_link", "test_id"));
        if (! isset($fields)) {
            return false;
        }
        $hash = $fields["auth_link"];
        $test_id = $fields["test_id"];
        $this->Test->rel();
        $test = $this->Test->read(array("jar_name"), $test_id);
        if (! isset($test[$this->Test->name]["jar_name"])) {
            return false;
        }
        $file_name = $test[$this->Test->name]["jar_name"] . ".jar";
        $this->addLineFromAppletsMapFile($hash, $file_name);
	}

    function delLineFromAppletsMapFile($hash)
    {
        $map = $this->getModel("Test")->getAppletsMap();
        if (isset($map[$hash])) {
            unset($map[$hash]);
        }
        $this->getModel("Test")->setAppletsMap($map);
    }

    function addLineFromAppletsMapFile($hash, $file_name)
    {
        $map = $this->getModel("Test")->getAppletsMap();
        $map[$hash] = $file_name;
        $this->getModel("Test")->setAppletsMap($map);
    }
}

?>